package com.idea.relax.datascope.config;

import com.idea.relax.datascope.DataScopeEnum;
import com.idea.relax.datascope.DefaultDataScopeConditionRegister;
import com.idea.relax.datascope.auth.IAuthUserService;
import com.idea.relax.datascope.IDataScopeConditionRegister;
import com.idea.relax.datascope.constant.SqlConstant;
import com.idea.relax.datascope.props.RelaxDataScopeProperties;
import com.idea.relax.tool.core.Func;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

import java.util.List;

/**
 * @className: RelaxDataScopeConfiguration
 * @description: TODO 类描述
 * @author: salad
 * @date: 2022/11/8
 **/
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(RelaxDataScopeProperties.class)
public class RelaxDataScopeConfiguration {


    @Bean
    public IDataScopeConditionRegister dataScopeConditionRegister(ObjectProvider<IAuthUserService> objectProvider){
        IAuthUserService authUserService = objectProvider.getIfAvailable();
        Assert.notNull(authUserService,"authUserService is not null!");
		IDataScopeConditionRegister register = new DefaultDataScopeConditionRegister();
        register.register(DataScopeEnum.OWN_DEPT,(type, column, boundSql, targetSql) -> {
            List<Number> deptId = authUserService.getUserDept();
            return String.format(SqlConstant.SELECT_PREFIX.concat(SqlConstant.WHERE),targetSql,column, Func.join(deptId));
        });
        register.register(DataScopeEnum.OWN,(type, column, boundSql, targetSql) -> {
            Number userId = authUserService.getUserId();
            return String.format(SqlConstant.SELECT_PREFIX.concat(SqlConstant.WHERE),targetSql,column, userId);
        });
        return register;
    }




}
